import { ColorEnum } from '@/enum/graph.enum.js'
import {
  createPallete,
  ditheringBurke,
  getClosestColor
} from './ditheringFilter.js'
import ditheringFilter from './ditheringFilter2.js'

export function getToken () {
  return sessionStorage.getItem('token')
}
export function ditherImageToBase64 ({ url, type = 'TYPE_A', palette = null }) {
  return new Promise((resolve, reject) => {
    if (!url) resolve()
    // 创建图片对象
    const image = new Image()
    image.src = url
    image.crossOrigin = 'Anonymous' // 设置跨域属性，允许加载其他域上的图片

    // 图片加载完成后执行
    image.onload = function () {
      // 创建一个Canvas元素
      const canvas = document.createElement('canvas')

      const ctx = canvas.getContext('2d')
      canvas.willReadFrequently = true
      // 设置Canvas的尺寸与图像相同
      canvas.width = image.width
      canvas.height = image.height

      // 在Canvas上绘制图像
      ctx.drawImage(image, 0, 0)

      // 获取Canvas中的图像数据
      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)

      // 应用抖动滤镜
      const ditheredImageData =
        type === 'TYPE_A'
          ? ditheringBurke(imageData, palette)
          : type === 'TYPE_B'
            ? ditheringFilter(imageData, palette)
            : imageData
      const colorPalette = createPallete(palette)
      for (let i = 0; i < ditheredImageData.data.length; i += 4) {
        const currentColor = [
          ditheredImageData.data[i],
          ditheredImageData.data[i + 1],
          ditheredImageData.data[i + 2]
        ]
        const closestColor = getClosestColor(currentColor, colorPalette)
        ditheredImageData.data[i] = closestColor[0]
        ditheredImageData.data[i + 1] = closestColor[1]
        ditheredImageData.data[i + 2] = closestColor[2]
      }
      // 将修改后的图像数据绘制回Canvas上
      ctx.putImageData(ditheredImageData, 0, 0)

      // 将Canvas中的图像转换为base64编码
      const base64 = canvas.toDataURL('image/jpeg')

      // 将base64编码传递给resolve函数
      resolve(base64)
    }

    // 图片加载失败时执行
    image.onerror = function () {
      reject(new Error('Failed to load image'))
    }
  })
}
export function getGraphColorList (str) {
  const list = []
  if (!str) {
    return list
  }
  str.split('_').forEach((item) => {
    const color = ColorEnum[item]
    if (color) {
      list.push(color)
    }
  })
  return list
}

export function getSize (str) {
  if (!str) {
    console.log('获取画布大小失败')
    return false
  }

  // 使用 split 方法将字符串按 * 分割成数组
  const parts = str.split('×')
  if (parts.length !== 2) {
    console.log('字符串格式错误')
    return false
  }

  const width = parseInt(parts[0].trim(), 10)
  const height = parseInt(parts[1].trim(), 10)

  if (isNaN(width) || isNaN(height)) {
    console.log('解析数字失败')
    return false
  }

  return {
    width,
    height
  }
}

export function serializeRequestForm (object) {
  return Object.entries(object).map(([key, value]) => ({
    K: key,
    V: value
  }))
}

export function getElementDistanceToBottom (element) {
  // 获取元素距离视口顶部的距离
  const elementRect = element.getBoundingClientRect()
  const elementTop = elementRect.top
  // 获取视口的高度
  const viewportHeight = window.innerHeight

  // 计算元素距离视口底部的距离
  return viewportHeight - elementTop
}
